#!/usr/bin/env python
# -- coding: utf-8 --
"""
@Time : 2022/3/11 16:32
@Coder: xh
@IDE : PyCharm
=========================
"""
import os

import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline, Grid
from pyecharts.commons.utils import JsCode
from xpinyin import Pinyin


def genre_rich(names):
    p = Pinyin()
    rich = {}
    for name in names:
        pinyin = p.get_pinyin(name, splitter='')
        rich[f'{pinyin}'] = {
            'width': 24,
            'height': 24,
            'align': 'center',
            'backgroundColor': {
                'image': f'./{name}.png'
            }
        }
    return rich


def make_chart(industry_cn, industry_en, year, month, color_str, play_interval) -> Timeline:
    print(f'正在制作{industry_en}_rank_bar_{year}{month}')
    if not os.path.exists(f'./charts/{industry_en}'):
        os.makedirs(f'./charts/{industry_en}')
    df = pd.read_csv(r'./rank_download/{}_202212.csv'.format(industry_en), encoding='utf8').sort_values(by=['date', 'value'])
    time_label = list(df['date'].unique())

    # def colours_genera(n):
    #     rangelist = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    #     n = int(n)
    #     colours = []  # 空列表，用于插入n个表示颜色的字符串
    #     j = 1
    #     while j <= n:  # 循环n次，每次在0到14间随机生成6个数，在加“#”符号，次次插入列表
    #         colour = ""  # 空字符串，用于插入字符组成一个7位的表示颜色的字符串（第一位为#，可最后添加）
    #         for i in range(6):
    #             colour += rangelist[random.randint(0, 14)]  # 用randint生成0到14的随机整数作为索引
    #         colour = "#" + colour  # 最后加上不变的部分“#”
    #         colours.append(colour)
    #         j = j + 1
    #     return colours

    # color_list = colours_genera(df.shape[0])
    # color_str = "['" + "','".join(color_list) + "']"

    # color_str = """
    # ['#d3c8ff', '#c8baff', '#bdacff', '#b19eff', '#a690ff', '#9b82ff', '#9075ff', '#8567ff', '#7a59ff', '#6f4bff']
    # """
    colour_js = JsCode("""
            function (params){
                    var colorList = %s;
                    return colorList[params.dataIndex];
                    }
    """ % f"""{color_str}""")
    formatter_js = JsCode("""
            function(params){
            var formate = '{'+params.data.pinyin+'|}    ' + params.value;
            return formate
            }
    """)

    tl = Timeline(init_opts=opts.InitOpts(width='1200px', height='675px',
                                          animation_opts=opts.AnimationOpts(animation_easing='linear'),
                                          renderer='svg'
                                          )
                  )
    for t in time_label:
        grid = Grid()
        xdata = list(df[df['date'] == t]['entityName'])
        ydata = list(df[df['date'] == t]['value'])
        p = Pinyin()
        data = [{'value': y, 'pinyin': p.get_pinyin(x, splitter='')} for x, y in zip(xdata, ydata)]
        bar = (
            Bar()
            .add_xaxis(xdata)
            .add_yaxis('', data,
                       category_gap="36%",
                       label_opts=opts.LabelOpts(position="right",
                                                 distance=5,
                                                 formatter=formatter_js,
                                                 rich=genre_rich(xdata)),
                       itemstyle_opts=opts.ItemStyleOpts(color=colour_js)
                       )
            .reversal_axis()
            .set_global_opts(
                legend_opts=opts.LegendOpts(is_show=False),
                title_opts=opts.TitleOpts(title=f"{year}年{month}月{industry_cn}行业品牌榜",
                                          pos_left='center', pos_top='5%',
                                          title_textstyle_opts=opts.TextStyleOpts(font_family='monospace')),
                yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(interval=0),
                                         axistick_opts=opts.AxisTickOpts(is_show=False)),
                xaxis_opts=opts.AxisOpts(axistick_opts=opts.AxisTickOpts(is_inside=True)),
                graphic_opts=opts.GraphicGroup(
                    graphic_item=opts.GraphicItem(left='center', width=1000, height=630),
                    children=[
                        opts.GraphicText(
                            graphic_item=opts.GraphicItem(left='10%', top='102%'),
                            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                text='排序规则：聚合品牌所有关键词，综合计算在百度网页、资讯、图片、视频、贴吧等各频道、 产品的品牌活跃度，包含了品牌相关的用户搜索行为、',
                                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill='#4F4F4F'),
                                font='monospace'
                            )
                        ),
                        opts.GraphicText(
                            graphic_item=opts.GraphicItem(left='10%', top='105%'),
                            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                text='用户资讯阅读行为、用户互动行为。求和搜索、资讯、互动行为形成品牌指数榜。',
                                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill='#4F4F4F'),
                                font='monospace'
                            )
                        ),
                        opts.GraphicText(
                            graphic_item=opts.GraphicItem(left='70%', top='70%'),
                            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                text=f'{t}',
                                font='64px monospace',
                                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill=color_str[0])
                            )
                        ),
                        opts.GraphicText(
                            graphic_item=opts.GraphicItem(left='80%', top='12%'),
                            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                text='数据来源：百度指数',
                                font='monospace',
                                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill=color_str[-1])
                            )
                        )
                    ]
                ),
            )
        )
        grid.add(bar, grid_opts=opts.GridOpts(pos_left='15%', pos_top='15%'))  # 使类别的标签不用旋转也能完全显示
        tl.add(grid, f"{t}")
        tl.add_schema(
            play_interval=play_interval,
            is_auto_play=True,
            is_timeline_show=False,
        )
    file_pre = "./charts/{}/rank_bar_{}{}".format(industry_en, year, month)
    tl.render(f"{file_pre}.html")
    return tl
